package cn.com.surker.workcon.service.bcs;

import cn.com.surker.base.system.entity.SysControlStorage;
import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.util.StringUtils;
import cn.com.surker.workcon.common.GKJDBCService;
import cn.com.surker.workcon.service.StorXMaterService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 中青林工控机的料仓对应
 * </p>
 *
 * @author admin
 * @since 2024-09-26
 */
public class StorXMaterServiceImpl extends GKJDBCService implements StorXMaterService {

	public Long insertStore(SysLine line, SysControlStorage controlStorage) {
		String sql = "insert into StorXMater (Storage,Material,DatTim,Station) values (?,?,?,?)";
		Object[] obj = {controlStorage.getName(), controlStorage.getMaterialName(), controlStorage.getControlCreateTime(), line.getControlLineId()};
		JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"});
				for (int i = 0; i < obj.length; i++) {
					ps.setObject(i + 1, obj[i]);
				}
				return ps;
			}
		}, keyHolder);
		Long taskId = keyHolder.getKey().longValue();
		if (taskId > 1)
			return taskId;
		return -1l;
	}

	public Long updateStore(SysLine line, SysControlStorage oldControlStorage, SysControlStorage controlStorage) {
		JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
		String querySql = "select * from StorXMater where station = " + line.getControlLineId()
			+ " and Storage = '" + oldControlStorage.getName() + "'";
		List<Map<String, Object>> mapList = jdbcTemplate.queryForList(querySql);
		if (mapList == null || mapList.size() == 0) {
			return insertStore(line, controlStorage);
		} else {
			String updateSql = "update StorXMater set Station=" + line.getControlLineId() + ",DatTim = '" + controlStorage.getControlCreateTime() + "' ";
			if (!StringUtils.isNull(controlStorage.getName()))
				updateSql += " ,Storage ='" + controlStorage.getName() + "' ";
			if (!StringUtils.isNull(controlStorage.getMaterialName()))
				updateSql += " ,Material ='" + controlStorage.getMaterialName() + "' ";
			updateSql += " where id = " + mapList.get(0).get("ID");
			Integer code = jdbcTemplate.update(updateSql);
			if (code > 0)
				return 0l;
			return -1l;
		}
	}
}
